package com.vic.framework.helper;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vic.framework.annotation.Component;
import com.vic.framework.annotation.Controller;
import com.vic.framework.annotation.Service;
import com.vic.framework.utils.ClassUtils;


/**
 * 类操作辅助类
 * @author VIC
 *
 */
public final class ClassHelper {

	/**
	 * 存放应用下的全部class
	 */
	private static final Set<Class<?>> CLASS_SET;
	
	static {
		String basePackage = ConfigHelper.getAppBasePath();
		CLASS_SET = ClassUtils.getClassSet(basePackage);
	}
	
	public static Set<Class<?>> getClassSet(){
		return CLASS_SET;
	}

	/**
	 * 获取所有service类
	 * @return
	 */
	public static Set<Class<?>> getServiceClassSet(){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		for(Class<?> cls : CLASS_SET) {
			if(cls.isAnnotationPresent(Service.class)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
	
	/**
	 * 获取所有Component类
	 * @return
	 */
	public static Set<Class<?>> getComponentClassSet(){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		for(Class<?> cls : CLASS_SET) {
			if(cls.isAnnotationPresent(Component.class)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
	
	/**
	 * 获取所有controller类
	 * @return
	 */
	public static Set<Class<?>> getControllerClassSet(){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		for(Class<?> cls : CLASS_SET) {
			if(cls.isAnnotationPresent(Controller.class)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
	/**
	 * 获取所有Bean类 包括service controller
	 * @return
	 */
	public static Set<Class<?>> getBeanClassSet(){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		classSet.addAll(getServiceClassSet());
		classSet.addAll(getControllerClassSet());
		classSet.addAll(getComponentClassSet());
		return classSet;
	}
	
	/**
	 * 获取应用包下的某父类或接口的所有子类或实现类
	 */
	public static Set<Class<?>> getClassSetBySuper(Class<?> superClass) {
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		for(Class<?> cls : CLASS_SET) {
			if(superClass.isAssignableFrom(cls) && superClass.equals(cls)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
	
	/**
	 * 获取应用包名下带有某注解的所有类
	 */
	public static Set<Class<?>> getClassByAnnotation(Class<? extends Annotation> annotationClass ) {
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		for(Class<?> cls :  CLASS_SET) {
			if(cls.isAnnotationPresent(annotationClass)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
}
